import 'package:flutter/material.dart';
import '../../routers/application.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:package_info/package_info.dart';
import '../../config/service_method.dart';
import 'package:flutter/services.dart';
import 'dart:convert';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'dart:io';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';



class Setting extends StatefulWidget{
    _SettingState createState() => _SettingState();
}
class _SettingState extends State<Setting>{

   
    // var _saveAPKLocalPath = "";

    @override
    void initState() {
        super.initState();
        FlutterDownloader.registerCallback((id, status, progress) async {
            print("id:${id}===== status=======:${status}=====progress======:${progress}");
            if (status == DownloadTaskStatus.complete) {
                var fileAdd = await _apkLocalPath;
                OpenFile.open(fileAdd+"/app-release.apk");
                FlutterDownloader.open(taskId: id);
            }
        });
    }


    @override
    Widget build(BuildContext context){
        return Scaffold(
            appBar: AppBar(
                // leading: 
                centerTitle: true,
                title: Text("设置")
            ),
            body: SingleChildScrollView(
                child: Container(
                    width: double.infinity,
                    child: Column(
                        children: <Widget>[
                            ListTile(
                                leading: Icon(Icons.lock),
                                title: Text("修改密码"),
                                trailing: Icon(Icons.arrow_forward_ios),
                                onTap: (){
                                    Application.router.navigateTo(context,"/modifyPassword");
                                },
                            ),
                            Divider(height: 5.0,color: Colors.grey),
                            ListTile(
                                leading: Icon(Icons.lock),
                                title: Text("检查更新APP版本"),
                                trailing: Icon(Icons.arrow_forward_ios),
                                onTap: _requestDownload,
                            ),
                            Divider(height: 5.0,color: Colors.grey),
                            // ListTile(
                            //     leading: Icon(Icons.lock),
                            //     title: Text("测试"),
                            //     trailing: Icon(Icons.arrow_forward_ios),
                            //     onTap: (){},
                            // ),
                            Container(
                                margin: EdgeInsets.only(top: 20.0),
                                child: FlatButton(
                                    color: Color.fromRGBO(81, 126, 219, 1),
                                    padding: EdgeInsets.fromLTRB(80.0, 15.0, 80.0, 15.0),
                                    shape:RoundedRectangleBorder(borderRadius: BorderRadius.circular(20.0)),
                                    child: Text(
                                        "退出登陆",
                                        style: TextStyle(
                                            color: Colors.white
                                        ),
                                    ),
                                    onPressed: _loginOut,
                                ),
                            )
                            
                        ],
                    ),
                ),
            ),
        );
    }

    void _loginOut() async{
    //4、销毁的方法
        // SharedPreferences prefs =await SharedPreferences.getInstance();
        // prefs.remove("loginToken");

        Future<dynamic> future = Future(()async{
            SharedPreferences prefs =await SharedPreferences.getInstance();
            prefs.remove("loginToken");
        });
        future.then((val){
            print("跳转到首页");
            Application.router.navigateTo(context,"/login");
        }).catchError((e){
            print(e);
        });
    }

    Future<String> get _apkLocalPath async {
        final directory = await getExternalStorageDirectory();
        print(directory.path.toString()+"00000000000000000000000000000");
        return directory.path.toString();
    }

    void _requestDownload() async {
        
        final taskId = await FlutterDownloader.enqueue(
            url: 'http://www.hengyiyun.com/imagefront/login/app-release.apk',
            savedDir: await _apkLocalPath,
            showNotification: true,
            openFileFromNotification:true, 
        );
    }

    void _checkNewVersion()async{
        PackageInfo.fromPlatform().then((PackageInfo packageInfo) async{
            
            // var data = {
            //     "version": packageInfo.version,
            // };
            // DioUtil.request('/tqes/web/login/check',formData: data).then((val){
            //     Map<String,dynamic> responseData = json.decode(val.toString());
            //     if(responseData["success"]){
            //         try{
            //             if(responseData["getNewVersion"]){

            //             }else{
            //                 Fluttertoast.showToast(
            //                     msg: "暂无新版本",
            //                     toastLength: Toast.LENGTH_SHORT,
            //                     gravity: ToastGravity.CENTER,
            //                     timeInSecForIos: 1,
            //                     // backgroundColor: Colors.pink,
            //                     // textColor: Colors.white,
            //                     fontSize: 16.0
            //                 );
            //            }
            //         }catch(e){
            //             print("json解析出现错误${e}");
            //             return;
            //         }
            //     }else{
            //         Fluttertoast.showToast(
            //             msg: responseData["msg"],
            //             toastLength: Toast.LENGTH_SHORT,
            //             gravity: ToastGravity.CENTER,
            //             timeInSecForIos: 1,
            //             // backgroundColor: Colors.pink,
            //             // textColor: Colors.white,
            //             fontSize: 16.0
            //         );
            //         return;
            //     }

            // });
        });
    }

}